package com.spark.demoim.global

import android.database.DatabaseErrorHandler
import android.util.Log
import com.hyphenate.EMCallBack

import com.hyphenate.EMConnectionListener
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import com.spark.demoim.utils.TaskProvider
import org.jetbrains.anko.doAsync

interface ConfigContract {
    interface ConfigPresenter {
        fun registerEMConnectionListener()
    }

    interface ConfigView {

    }

    interface ConfigAsyncView {
        fun fetchGroups(emCallBack: EMCallBack?)
        fun fetchContacts(emCallBack: EMCallBack?)
        fun fetchBlacklist(emCallBack: EMCallBack?)
        fun notifyGroups(succeed: Boolean)
        fun notifyContacts(succeed: Boolean)
        fun notifyBlacklist(succeed: Boolean)

    }


    class DefaultConfigPresenter(// V(MVP)
            private val configAsyncView: ConfigAsyncView) : ConfigPresenter {
        // 群组正在同步
        private var isSyncingGroupsWithServer = false
        // 联系人正在同步
        private var isSyncingContactsWithServer = false
        // 黑名单列表正在同步
        private var isSyncingBlackListWithServer = false
        // 群组同步完毕
        private var isGroupsSyncedWithServer = false
        // 联系人同步完毕
        private var isContactsSyncedWithServer = false
        // 黑名单同步完毕
        private var isBlackListSyncedWithServer = false

        companion object {
            private val TAG = DefaultConfigPresenter::class.java.simpleName
        }

        /**
         * 注册 EMConnection 连接
         */
        override fun registerEMConnectionListener() {
            val emConnectionListener = object : EMConnectionListener {
                override fun onConnected() {
                    if (isGroupsSyncedWithServer && isContactsSyncedWithServer)
                        Log.e(TAG, "群组和联系人已经同步完毕")
                    else {
                        if (!isGroupsSyncedWithServer)
                            configAsyncView.fetchGroups(null)
                        if (!isContactsSyncedWithServer)
                            configAsyncView.fetchContacts(null)
                        if (!isBlackListSyncedWithServer)
                            configAsyncView.fetchBlacklist(null)
                    }
                }

                override fun onDisconnected(i: Int) {

                }
            }

            EMClient.getInstance().addConnectionListener(emConnectionListener)
        }

        /**
         * 群组同步
         */
        fun asyncFetchGroups(emCallBack: EMCallBack?) {
            if (isSyncingGroupsWithServer) return
            isSyncingGroupsWithServer = true
            doAsync {
                try {
                    EMClient.getInstance().groupManager().joinedGroupsFromServer
                    // 避免服务返回时用户退出,所以应立即执行
                    if (!isLoggedInBefore()) {
                        isGroupsSyncedWithServer = false
                        isSyncingContactsWithServer = false
                        configAsyncView.notifyGroups(false)
                        return@doAsync
                    }
                    //todo demoModel.setGroupsSynced(true)
                    isGroupsSyncedWithServer = true
                    isSyncingGroupsWithServer = false
                    configAsyncView.notifyGroups(true)
                    emCallBack?.onSuccess()
                } catch (e: HyphenateException) {
                    //todo demoModel.setGroupsSynced(false)
                    isGroupsSyncedWithServer = false
                    isSyncingGroupsWithServer = false
                    emCallBack?.onError(e.errorCode, e.toString())
                }
            }
        }

        /**
         * 联系人同步
         */
        fun asyncFetchContacts(emCallBack: EMCallBack?) {
            if (isSyncingContactsWithServer) return
            isSyncingContactsWithServer = true
            doAsync {
                var usernames = listOf<String>()
                try {
                    usernames = EMClient.getInstance().contactManager().allContactsFromServer
                } catch (e: HyphenateException) {
                }
            }
        }


        /**
         * 之前是否已经登陆
         */
        fun isLoggedInBefore(): Boolean {
            return EMClient.getInstance().isLoggedInBefore
        }
    }
}